<?php

namespace backend\models;

use Yii;
use common\models\UserInfo;

/**
 * This is the model class for table "pay_user_discount".
 *
 * @property integer $id
 * @property integer $user_type
 * @property integer $user_type_class
 * @property integer $sales_type
 * @property integer $post_sales_service
 * @property string $discount_rate
 */
class PayUserDiscount extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pay_user_discount';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['id', 'user_type', 'user_type_class', 'sales_type', 'post_sales_service'], 'integer'],
            [['discount_rate'], 'number']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'user_type' => Yii::t('app', 'User Type'),
            'user_type_class' => Yii::t('app', 'User Type Class'),
            'sales_type' => Yii::t('app', 'Sales Type'),
            'post_sales_service' => Yii::t('app', 'Post Sales Service'),
            'discount_rate' => Yii::t('app', 'Discount Rate'),
        ];
    }
    public static function getUserDiscountByUserid($user_id)
    {
        $res=UserInfo::findOne(['id'=>$user_id]);
        if (!empty($res)){
            return self::getUserDiscountByTypeClass($res->user_type, $res->user_type_class);
        }
        else {
            return null;
        }
    }
    public static function getUserDiscountByTypeClass($user_type,$user_type_class)
    {
        $user_discount=array();
        $default_service=0;
        $service_count=1;
        $i=0;
        $res=self::find()->where(['user_type'=>$user_type,'user_type_class'=>$user_type_class])->asArray()->all();
        foreach($res as $row) {
            if (!isset($user_discount[$row['sales_type']])) {
                $user_discount[$row['sales_type']]=array();
            }
            $user_discount[$row['sales_type']]=[
                'discount'=>$row['discount_rate'],
                'service'=>$row['post_sales_service']
            ];
        }
        return $user_discount;
    }
}
